import config from '@/app.config.js'
const tokenKey = config.lzy.storageKey + '-token';
const domain = config.lzy.domain;

const utils = {
	//接口地址
	interfaceUrl: function() {
		return domain
	},
	delayed: null,
	toast: function(text, duration, success) {
		uni.showToast({
			title: text || "出错啦~",
			icon: success || 'none',
			duration: duration || 2000
		})
	},
	modal: function(title, content, showCancel = false, callback, confirmColor, confirmText, cancelColor,
		cancelText) {
		uni.showModal({
			title: title || '提示',
			content: content,
			showCancel: showCancel,
			cancelColor: cancelColor || "#555",
			confirmColor: confirmColor || "#e41f19",
			confirmText: confirmText || "确定",
			cancelText: cancelText || "取消",
			success(res) {
				if (res.confirm) {
					callback && callback(true)
				} else {
					callback && callback(false)
				}
			}
		})
	},
	/**
	 * 请求数据处理
	 * @param string url 请求地址 。支持输入完整的请求地址，以http或https开头。modify by LZy on 2023.8.13
	 * @param {*} postData 请求参数
	 * @param string method 请求方式
	 *  GET or POST
	 * @param string contentType 数据格式
	 *  'application/x-www-form-urlencoded'
	 *  'application/json'
	 * @param bool isDelay 是否延迟显示loading
	 * @param bool hideLoading 是否隐藏loading
	 *  true: 隐藏
	 *  false:显示
	 * @param string loadingTitle loading显示的文字
	 * @param function callback 回调函数。登录过期的场景，重新登录后要重新调用的页面取数据函数，如getData，getList等
	 */
	request: function(url, postData = {}, method = "GET", contentType = "application/x-www-form-urlencoded",
		isDelay, hideLoading,
		loadingTitle, callback) {
		//接口请求
		let loadding = false;
		utils.delayed && uni.hideLoading();
		clearTimeout(utils.delayed);
		utils.delayed = null;
		if (!hideLoading) {
			utils.delayed = setTimeout(() => {
				uni.showLoading({
					mask: true,
					title: loadingTitle || '请稍候...',
					success(res) {
						loadding = true
					}
				})
			}, isDelay ? 1000 : 0)
		}
		// if(!contentType) contentType = "application/x-www-form-urlencoded";
		contentType = "application/json";

		// console.log('封装request-token', utils.getToken())	
		return new Promise((resolve, reject) => {
			uni.request({
				url: url.indexOf("http") == 0 ? url : (utils.interfaceUrl() + url),
				data: postData,
				header: {
					'content-type': contentType,
				},
				method: method, //'GET','POST'
				dataType: 'json',
				timeout: 15000, // 15秒超时
				withCredentials: true,
				success: (res) => {
					if (res.statusCode === 200) {
						if (res.data.RetCode === 1) resolve(res.data);
						else {
							console.error('====request返回错误', res)
							reject(res.data.Msg);
						}
					} else {
						console.error('====request返回错误', res)
						reject(res.msg || res.statusCode);
					}
				},
				fail: (res) => {
					console.error('====request失败', res)
					utils.toast("网络不给力，请稍后再试~")
					reject(res)
				},
				complete: function(res) {
					if (!hideLoading) {
						uni.hideLoading()
					}
					clearTimeout(utils.delayed)
					utils.delayed = null;
					if (res.statusCode === 200) {

					} else {
						utils.toast('服务器开小差了~' + res.statusCode);
					}
				}
			})
		})
	},
	/**
	 * 上传文件
	 * @param string url 请求地址
	 * @param string src 文件路径
	 */
	uploadFile: function(url, src, header, formData, file) {
		uni.showLoading({
			title: '正在上传...'
		})
		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url: url.indexOf("http") == 0 ? url : (utils.interfaceUrl() + url),
				filePath: src,
				// name: 'file',
				name: 'image',
				// files:[{
				// 	name: 'image',
				// 	file,
				// 	uri: src
				// }],
				header: {
					'content-type': 'multipart/form-data'
				},
				formData,
				success: function(res) {
					console.log('上传文件success', res)
					uni.hideLoading()
					let data = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
					
					// console.log('上传文件successdata', data)
					
					if (data.RetCode == 1) {
						//返回图片地址
						resolve(data)
					} else {
						utils.toast(data.Msg);
					}
				},
				fail: function(res) {
					console.log('上传文件fail', res)
					utils.toast("网络不给力，请稍后再试~")
					reject(res)
				}
			})
		})
	},
	//设置token
	setToken: function(token) {
		uni.setStorageSync(tokenKey, token)
	},
	//获取token
	getToken: function() {
		// return uni.getStorageSync(tokenKey)
		return vk.getVuex('$user.token');
	},
}

module.exports = {
	interfaceUrl: utils.interfaceUrl,
	request: utils.request,
	uploadFile: utils.uploadFile,
	setToken: utils.setToken,
	getToken: utils.getToken,
	toLogin: utils.toLogin,
}